# encoding: utf-8
from __future__ import division
from PIL import Image, ImageDraw
from tqdm import tqdm

import os
import face_recognition
import imghdr
import sys


def get_all_files(path_dir):
    all_file = []
    for dir_path, dir_names, filenames in os.walk(path_dir):
        for dir_ in dir_names:
            all_file.append(os.path.join(dir_path, dir_))
        for name in filenames:
            all_file.append(os.path.join(dir_path, name))
    return all_file


def get_image_file(file_check):
    if os.path.isfile(file_check):
        if imghdr.what(file_check) == 'png':
            unknown_picture = face_recognition.load_image_file(file_check)
            unknown_face_encoding_list = face_recognition.face_encodings(unknown_picture)
            if len(unknown_face_encoding_list) > 0:
                unknown_face_encoding = unknown_face_encoding_list[0]
                results = face_recognition.compare_faces([my_face_encoding], unknown_face_encoding, tolerance=0.38)
                if results[0]:
                    return file_check


if __name__ == '__main__':
    picture_of_me = face_recognition.load_image_file(
        "../test_images/wuyanzu.png")
    my_face_encoding = face_recognition.face_encodings(picture_of_me)[0]

    resultList = []

    path = "../tests/test_images/"
    files = get_all_files(path)
    num_tasks = len(files)
    for file in tqdm(files):
        fileTarget = get_image_file(file)
        print("fileTarget", fileTarget)
        if fileTarget is not None:
            resultList.append(file)
            break
    print("定位:")
    image = face_recognition.load_image_file(resultList[0])
    pil_image = Image.fromarray(image)
    pil_image.show()
    print(resultList)
    sys.exit()
